package org.xs.web.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XML {

	
	public static Element getElementRoot(InputStream inputStream) throws DocumentException{
		SAXReader reader = new SAXReader();
		reader.setEntityResolver(new NullEntityResolver());
		reader.setMergeAdjacentText(true);
		return reader.read(inputStream).getRootElement();
	}
	
	public static Element getElmenetRootIfEmptyThrowRuntimeException(InputStream in){
		try {
			return getElementRoot(in);
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static class NullEntityResolver implements EntityResolver{
		private static final byte[] empty = new byte[0];
		@Override
		public InputSource resolveEntity(String publicId, String systemId)
				throws SAXException, IOException {
			return new InputSource(new ByteArrayInputStream(empty));
		}
		
	}
}
